package cn.wrl.config;

import cn.wrl.filter.AuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class RoutesConfiguration {

    @Autowired
    private KeyResolver hostNameResolver;

    @Autowired
    @Qualifier("redisLimiterUser")
    private RedisRateLimiter redisLimiterUser;

    @Autowired
    @Qualifier("redisLimiterItem")
    private RedisRateLimiter redisLimiterItem;

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder, AuthFilter authFilter) {
        return builder.routes()
                //route > 登录校验
                .route(r -> r.path("/address/list", "/userInfo/**", "/center/**")
                        .filters(f -> f.filter(authFilter))
                        .uri("lb://FOODIE-USER-SERVICE"))

                //route > 刷新token
                .route(r -> r.path("/auth-service/refresh")
                        .uri("lb://FOODIE-AUTH-SERVICE"))

                // todo search模块，主搜接口，轮播图接口
//                .route(r -> r.path("/search/**", "index/**", "items/search", "items/catItems")
//                        .uri("lb://FOODIE-SEARCH-SERVICE"))

                //route > 用户模块
                .route(r -> r.path("/address/**", "/passport/**", "/userInfo/**", "/center/**")
                        .filters(f -> f.requestRateLimiter(c -> {
                            c.setKeyResolver(hostNameResolver);
                            c.setRateLimiter(redisLimiterUser);
                            c.setStatusCode(HttpStatus.BAD_GATEWAY);
                        }))
                        .uri("lb://FOODIE-USER-SERVICE"))

                // route > 商品模块
                .route(r -> r.path("/items/**")
//                        .filters(f -> f.requestRateLimiter(c -> {
//                            c.setKeyResolver(hostNameResolver);
//                            c.setRateLimiter(redisLimiterItem);
//                        }))
                        .uri("lb://FOODIE-ITEM-SERVICE"))

                .route(r -> r.path("/shopcart/**")
                        .uri("lb://FOODIE-CART-SERVICE"))

                .route(r -> r.path("/orders/**", "/myorders/**", "/mycomments/**")
                        .uri("lb://FOODIE-ORDER-SERVICE"))

                .build();
    }

}
